package com.inspur.cloud.service.dataspace;

import com.inspur.cloud.dao.dataspace.HiveResourceDao;
import com.inspur.cloud.dao.dataspace.UserDao;
import com.inspur.cloud.dao.dataspace.UserResourceRelationDao;
import com.inspur.cloud.entity.dataspace.HiveResourceEntity;
import com.inspur.cloud.entity.dataspace.UserEntity;
import com.inspur.cloud.entity.dataspace.UserResourceRelationEntity;
import com.inspur.cloud.entity.dataspace.ao.resource.DistributeAO;
import com.inspur.cloud.entity.dataspace.common.OpEntityResult;
import com.inspur.cloud.entity.dataspace.common.PageReqParam;
import com.inspur.cloud.entity.dataspace.common.PageResult;
import com.inspur.cloud.entity.dataspace.dto.UserResourceRelationDTO;
import com.inspur.cloud.entity.dataspace.vo.HiveAddVO;
import com.inspur.cloud.entity.dataspace.vo.HiveReq;
import com.inspur.cloud.entity.dataspace.vo.HiveVO;
import com.inspur.cloud.enums.PermissionEnum;
import com.inspur.cloud.enums.ResourceTypeEnum;
import com.inspur.cloud.exception.ApiException;
import com.inspur.cloud.security.AuthorizationHelper;
import com.inspur.cloud.util.StringUtil;
import com.inspur.cloud.util.TConstants;
import com.inspur.cloud.util.TimeHelper;
import com.inspur.cloud.util.UtilTenant;
import org.apache.commons.lang.StringUtils;
import org.apache.http.auth.AUTH;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HiveManagerService {
    @Autowired
    private HiveResourceService hiveResourceService;
    @PersistenceContext
    private EntityManager em;
    @Autowired
    UserService userService;
    @Autowired
    UserResRelationSerivce userResRelationSerivce;
    @Autowired
    RangerService rangerService;
    @Autowired
    HiveService hiveService;
    @Autowired
    UserResourceRelationService userResourceRelationService;
    @Autowired
    ClusterConfigUtil clusterConfigUtil;
    @Autowired
    AuthService authService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public PageResult<HiveVO> getList(PageReqParam<HiveReq> hiveReq) {
        Integer level = 0;
        PageResult<HiveVO> ret = new PageResult<>();
        if (hiveReq.getReqParam().getResourceId().equals(0)) {
            level = 1;
        } else {
            HiveResourceEntity HiveResourceEntity = hiveResourceService.findHiveResourceEntityById(hiveReq.getReqParam().getResourceId());
            if (HiveResourceEntity == null) {
                ret.setCount(1L);
                ret.setMsg("当前资源ID不存在");
                ret.setCode(-1);
                return ret;
            }
            level = HiveResourceEntity.getLevel() + 1;
        }

        StringBuilder sql = new StringBuilder("SELECT h.* FROM hive_resource h ");
        StringBuilder countSql = new StringBuilder("SELECT count(*) from (SELECT count(*) FROM hive_resource h ");
        StringBuilder condition = new StringBuilder(" WHERE  h.status=1 ");
        UserEntity currentUser = AuthorizationHelper.getUser();

        if (hiveReq.getReqParam().getType() == 1) {
            condition.append(" AND h.owner=1 ");
        } else if (hiveReq.getReqParam().getType() == 2) {
            if (AuthorizationHelper.isAdmin()) {
                condition.append(" AND h.owner !=").append(TConstants.ADMIN_ID);
            } else if (AuthorizationHelper.isTenant()) {
                condition.append(" AND h.owner=").append(currentUser.getId());
            } else {
                //显示上级租户私有资源下创建并分配给用户的资源
                UserEntity parent = userService.findUserById(AuthorizationHelper.getUser().getParentId());
                condition.append(" AND h.owner=").append(parent.getId());
            }
        } else {
            if (AuthorizationHelper.isUser()) {//既不是自己，也不是管理员，也不是自己的上级
                UserEntity parent = userService.findUserById(AuthorizationHelper.getUser().getParentId());
                condition.append(" AND h.owner!=1 AND h.owner!=").append(currentUser.getId());
                if (parent != null) {
                    condition.append(" AND h.owner!=").append(parent.getId());
                }
            } else {
                condition.append(" AND h.owner!=1 AND h.owner!=").append(AuthorizationHelper.getUser().getId());
            }
        }
        if (!StringUtil.isEmpty(hiveReq.getReqParam().getResourceName())) {
            if (level==1) {//顶级
                condition.append(" AND h.database_name  like '%").append(hiveReq.getReqParam().getResourceName()).append("%'");
            } else if(level==2){
                condition.append(" AND (h.table_name  like '%").append(hiveReq.getReqParam().getResourceName()).append("%' ")
                        .append(" OR h.column_name like '%").append(hiveReq.getReqParam().getResourceName()).append("%') ");
            }else{
                condition.append(" AND h.column_name like '%").append(hiveReq.getReqParam().getResourceName()).append("%' ");
            }
        }
        condition.append(" AND h.parent_id= ").append(hiveReq.getReqParam().getResourceId());
        if (!AuthorizationHelper.isAdmin()) {
            Specification<UserResourceRelationEntity> specification = (Specification<UserResourceRelationEntity>) (root, query, cb) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(cb.equal(root.get("userId"), currentUser.getId()));
                list.add(cb.equal(root.get("resourceType"), ResourceTypeEnum.HIVE.name()));
                return cb.and(list.toArray(new Predicate[list.size()]));
            };
            List<UserResourceRelationEntity> urList = userResRelationSerivce.findAll(specification);
            List<Integer> dbNameList = new ArrayList<>();
            List<Integer> tableNameList = new ArrayList<>();
            List<Integer> columnNameList = new ArrayList<>();
            //如果用户有一个库，那就找出这个库所拥有的表和列族，反之如果给了它一个表，就要往上找到它的库（用于显示）
            for (UserResourceRelationEntity ur : urList) {
                if (ur.getResourceLevel() == 1) {
                    dbNameList.add(ur.getResourceId());//其所拥有的库
                    if (level >= 2) {//这个时候需要向下找了
                        List<Integer> tableUnder = hiveResourceService.findIdByParentId(ur.getResourceId());
                        if (tableUnder != null && tableUnder.size() > 0) {
                            tableNameList.addAll(tableUnder);
                            if (level >= 3) {
                                for (Integer tid : tableUnder) {
                                    List<Integer> columnUnder = hiveResourceService.findIdByParentId(tid);
                                    if (columnUnder != null && columnUnder.size() > 0) {
                                        columnNameList.addAll(columnUnder);
                                    }
                                }
                            }
                        }
                    }
                } else if (ur.getResourceLevel() == 2) {
                    tableNameList.add(ur.getResourceId());
                    //再向上去根据表ID找库ID
                    HiveResourceEntity HIVE = hiveResourceService.findHiveResourceEntityById(ur.getResourceId());
                    if (HIVE != null) {
                        dbNameList.add(HIVE.getParentId());
                    }
                    if (level == 3) {
                        List<Integer> columnUnder = hiveResourceService.findIdByParentId(ur.getResourceId());
                        if (columnUnder != null && columnUnder.size() > 0) {
                            columnNameList.addAll(columnUnder);
                        }
                    }
                } else {
                    columnNameList.add(ur.getResourceId());//加入列
                    HiveResourceEntity columnFamily = hiveResourceService.findHiveResourceEntityById(ur.getResourceId());
                    if (columnFamily != null) {
                        tableNameList.add(columnFamily.getParentId());//向上找表
                        HiveResourceEntity table = hiveResourceService.findHiveResourceEntityById(columnFamily.getParentId());
                        if (table != null) {//向上找库
                            dbNameList.add(table.getParentId());
                        }
                    }
                }
            }
            String ids;
            if (level == 1) {
                ids = StringUtil.concatIntListDistinct(dbNameList, ",");
            } else if (level == 2) {
                ids = StringUtil.concatIntListDistinct(tableNameList, ",");
            } else {
                ids = StringUtil.concatIntListDistinct(columnNameList, ",");
            }
            if (!StringUtil.isEmpty(ids)) {
                condition.append(" AND h.id in ( ").append(ids).append(" )");
            } else {
                ret.setCount(0L);
                ret.setMsg("查询结果为空.");
                ret.setCode(1);
                return ret;
            }
        }
        if (level == 1) {
            condition.append(" AND h.database_name NOT IN (").append(TConstants.HIVEDATABASEHIDDEN).append(") ");
        }
        condition.append(" group by h.id  ");
        countSql.append(condition).append(") aa ");
        sql.append(condition).append(" ORDER BY h.upd_date  DESC limit :limit ,:offset ");
        Query countQuery = em.createNativeQuery(countSql.toString());
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Integer limit = (hiveReq.getPageIndex() - 1) * hiveReq.getPageSize();
        Query listQuery = em.createNativeQuery(sql.toString());
        listQuery.setParameter("limit", limit);
        listQuery.setParameter("offset", hiveReq.getPageSize());
        listQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> result = listQuery.getResultList();
        List<HiveVO> voList = new ArrayList<>();
        //获取父资源的权限
        Integer resourceId = hiveReq.getReqParam().getResourceId();
        UserResourceRelationEntity parentUserRelation = null;
        if (resourceId != 0) {
            parentUserRelation = userResRelationSerivce.findFirstByResourceIdAndUserIdAndResourceType(resourceId, currentUser.getId(), ResourceTypeEnum.HIVE.name());
            HiveResourceEntity hiveResourceEntity = hiveResourceService.findHiveResourceEntityById(resourceId);
            while (parentUserRelation == null) {//如果父资源权限找不到
                hiveResourceEntity = hiveResourceService.findHiveResourceEntityById(hiveResourceEntity.getParentId());//找爷爷
                if (hiveResourceEntity == null) {
                    break;
                }
                parentUserRelation = userResRelationSerivce.findFirstByResourceIdAndUserIdAndResourceType(hiveResourceEntity.getId(), currentUser.getId(), ResourceTypeEnum.HIVE.name());//找爷爷的权限
            }
        }
        for (Map map : result) {
            HiveVO vo = new HiveVO();
            vo.setDatabaseName(map.get("database_name") != null ? map.get("database_name").toString().toLowerCase() : "");
            vo.setTableName(map.get("table_name") != null ? map.get("table_name").toString().toLowerCase() : "");
            vo.setColumnName(map.get("column_name") != null ? map.get("column_name").toString().toLowerCase() : "");
            vo.setResourceId(Integer.valueOf(map.get("id").toString()));
            UserResourceRelationEntity userResourceRelationEntity = userResRelationSerivce.findFirstByResourceIdAndUserIdAndResourceType(vo.getResourceId(), AuthorizationHelper.getUser().getId(), ResourceTypeEnum.HIVE.name());
            if (userResourceRelationEntity != null && !StringUtil.isEmpty(userResourceRelationEntity.getAuthor())) {
                vo.setPowerList(userResourceRelationEntity.getAuthor());
            } else {
                vo.setPowerList(parentUserRelation != null ? parentUserRelation.getAuthor() : "");
            }
            vo.setParentId(map.get("parent_id") != null ? Integer.valueOf(map.get("parent_id").toString()) : 0);
            vo.setLevel(map.get("level") != null ? Integer.valueOf(map.get("level").toString()) : 0);
            UserResourceRelationDTO userResourceRelationDTO = userResourceRelationService.queryUserByResourceIdExceptOwner(vo.getResourceId(), ResourceTypeEnum.HIVE, AuthorizationHelper.getUser().getId());
            vo.setTenantList(userResourceRelationDTO.getTannetList());
            vo.setUserList(userResourceRelationDTO.getUserList());
            if (vo.getLevel() == 2) {//如果是表，还需要显示列数
                vo.setColumnNum(hiveResourceService.findSonNum(vo.getResourceId()));
            }
            vo.setInsDate(map.get("ins_date") != null ? TimeHelper.StringToDate(map.get("ins_date").toString()) : null);
            vo.setUpdDate(map.get("upd_date") != null ? TimeHelper.StringToDate(map.get("upd_date").toString()) : null);
            vo.setOwner(map.get("owner") != null ? Integer.valueOf(map.get("owner").toString()) : 0);
            Integer creator = map.get("creator") != null ? Integer.valueOf(map.get("creator").toString()) : null;
            if (creator != null) {//hive的表和列创建者来自后台,这里大概率是取不到的
                UserEntity user = userService.findUserById(creator);
                vo.setCreator(user == null ? "" : user.getName());
            }
            voList.add(vo);
        }
        ret.setPageList(voList);
        ret.setCount(count.longValue());
        return ret;

    }


    // @Transactional(rollbackFor = Exception.class)
    public OpEntityResult<Integer> addRes(HiveAddVO HiveVO, UserEntity toUser) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        Date now = new Date();
        List<UserEntity> userList = new ArrayList<>();
        HiveResourceEntity hiveResourceEntity = new HiveResourceEntity();
        String powerStr = StringUtil.isEmpty(HiveVO.getPowerList()) ? PermissionEnum.getAllPermissionByType(ResourceTypeEnum.HIVE.getType()) : HiveVO.getPowerList();
        HiveResourceEntity exist = hiveResourceService.findByDatabaseName(HiveVO.getDatabaseName().toLowerCase());
        if (exist != null) {
            opEntityResult.setCode(-1);
            opEntityResult.setMsg("要创建的库已存在");
            return opEntityResult;
        }
        hiveResourceEntity.setDatabaseName(HiveVO.getDatabaseName().toLowerCase());
        hiveResourceEntity.setParentId(0);
        hiveResourceEntity.setLevel(1);
        hiveResourceEntity.setStatus(TConstants.RES_STATUS_AVAILABLE);
        hiveResourceEntity.setOwner(toUser.getId());
        hiveResourceEntity.setInsDate(now);
        hiveResourceEntity.setUpdDate(now);
        hiveResourceEntity.setCreator(AuthorizationHelper.getUser().getId());
        if (HiveVO.getTenantList() != null) {
            userList = userService.findByNameIn(HiveVO.getTenantList());
        }
        if (HiveVO.getUserList() != null) {
            userList.addAll(userService.findByNameIn(HiveVO.getUserList()));
        }
        if (HiveVO.getTenantIdList() != null) {
            userList = userService.findByIdIn(HiveVO.getTenantIdList());
        }
        if (HiveVO.getUserIdList() != null) {
            List<UserEntity> list = userService.findByIdIn(HiveVO.getUserIdList());
            userList.addAll(list);
        }
        //把创建者自己加入资源分配表
        userList.add(toUser);
        hiveResourceService.save(hiveResourceEntity);
        hiveService.createDatabase(hiveResourceEntity.getDatabaseName());

        if (userList != null && userList.size() > 0) {
            List<String> nameList = new ArrayList<>();
            String content = hiveResourceEntity.getDatabaseName() + "|*|*";
            for (UserEntity userEntity : userList) {
                UserResourceRelationEntity ur = new UserResourceRelationEntity();
                ur.setResourceId(hiveResourceEntity.getId());
                ur.setInsDate(now);
                ur.setUpdDate(now);
                ur.setStatus(1);
                ur.setUserId(userEntity.getId());
                ur.setResourceType(ResourceTypeEnum.HIVE.name());
                ur.setResourceContent(hiveResourceEntity.getDatabaseName());
                ur.setAuthor(powerStr);
                ur.setResourceLevel(hiveResourceEntity.getLevel());
                userResRelationSerivce.save(ur);
                nameList.add(userEntity.getName());//一次赋权，优化效率
            }//end for
            rangerService.setPermissionInRanger(ResourceTypeEnum.HIVE.name().toLowerCase(), content, powerStr, StringUtil.concat(nameList, "|"));
        }//end user list
        opEntityResult.setCode(1);
        opEntityResult.setMsg("hive资源创建成功");
        opEntityResult.setData(hiveResourceEntity.getId());
        return opEntityResult;
    }


    // @Transactional(rollbackFor = Exception.class)
    public OpEntityResult<Integer> distributeRes(DistributeAO hiveVO) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        HiveResourceEntity hiveResourceEntity = hiveResourceService.findHiveResourceEntityById(hiveVO.getResourceId());
        if (hiveResourceEntity == null) {
            return new OpEntityResult<>(-1, "指定的资源不存在", -1);
        }
        Integer result = userResourceRelationService.distribute(hiveVO, ResourceTypeEnum.HIVE, false);
        opEntityResult.setCode(1);
        if(UtilTenant.empty(hiveVO)) {
            opEntityResult.setMsg("分配已置空");
        }else{
            opEntityResult.setMsg("hive 资源分配成功");
        }
        opEntityResult.setData(result);
        return opEntityResult;
    }

    //@Transactional(rollbackFor = Exception.class)
    public OpEntityResult<Integer> share(DistributeAO hiveVO) throws Exception {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        HiveResourceEntity hiveResourceEntity = hiveResourceService.findHiveResourceEntityById(hiveVO.getResourceId());
        if (hiveResourceEntity == null) {
            return new OpEntityResult<>(-1, "指定的资源不存在", -1);
        }
        if(hiveResourceEntity.getLevel()!=null && hiveResourceEntity.getLevel()<=1){
            return new OpEntityResult<>(-1, "数据库不允许分享", -1);
        }
        Integer result = userResourceRelationService.distribute(hiveVO, ResourceTypeEnum.HIVE, true);
        opEntityResult.setCode(1);
        if(UtilTenant.empty(hiveVO)) {
            opEntityResult.setMsg("分享已置空");
        }else{
            opEntityResult.setMsg("hive 资源分享成功");
        }
        opEntityResult.setData(result);
        return opEntityResult;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    public OpEntityResult<Integer> delRes(Integer resourceId, Integer keepData) {
        OpEntityResult<Integer> opEntityResult = new OpEntityResult<>();
        HiveResourceEntity hive = hiveResourceService.findHiveResourceEntityById(resourceId);
        if (hive == null) {
            return new OpEntityResult<>(1, "指定的资源已经不存在", -1);
        }
        UserEntity currentUser = AuthorizationHelper.getUser();
        if(!AuthorizationHelper.isAdmin()) {
            String auth = authService.getSourceAuth(resourceId, currentUser.getId(), ResourceTypeEnum.HIVE.name());
            if (StringUtils.isEmpty(auth) || !auth.contains("drop")) {
                if (!currentUser.getId().equals(hive.getCreator())) {//如果没有权限，也不是创建者本人
                    throw new ApiException("无权删除该资源");
                }
            }
        }
        if (hive.getLevel() == 1) {//删库，清空权限
            if (keepData == 0) {//不保留数据
                if (existDatabase(hive.getDatabaseName())) {//存在才去调接口，否则按脏数据算，直接删除
                    hiveService.dropDatabaseForce(hive.getDatabaseName());
                }
            }
            delDatabase(hive, keepData);
        } else if (hive.getLevel() == 2) {//删表，只需要删数据库的字段即可，不需要再调大数据接口
            if (keepData == 0) {
                hiveService.dropTable(hive.getDatabaseName(), hive.getTableName());
            }
            delTable(hive, keepData);
        } else if (hive.getLevel() == 3) {//删列 ，服务器没删列功能
            delColumn(hive, keepData);
        }
        opEntityResult.setCode(1);
        opEntityResult.setMsg("hive资源已删除");
        opEntityResult.setData(1);
        return opEntityResult;
    }

    // @Transactional(rollbackFor = Exception.class)
    public OpEntityResult<Integer> sync(Integer resourceId, String resourceName) {
        OpEntityResult<Integer> result = new OpEntityResult(1, "同步成功", 0);
        Date now = new Date();
        String powerStr = PermissionEnum.getAllPermissionByType(ResourceTypeEnum.HIVE.getType());
        HiveResourceEntity parent = null;
        UserEntity currentUser = AuthorizationHelper.getUser();
        if (resourceId != 0) {
            parent = hiveResourceService.findHiveResourceEntityById(resourceId);
            if (parent == null) {
                return OpEntityResult.fail("父级资源不存在，不能同步其下的资源");
            }
            UserResourceRelationEntity parentUr = userResRelationSerivce.findFirstByResourceIdAndUserIdAndResourceType(parent.getId(), currentUser.getId(), ResourceTypeEnum.HIVE.name());
            if (parentUr != null) {
                powerStr = parentUr.getAuthor();
            }
        }

        Integer up = 0;//记录本次更新的条数
        Integer level;//当前资源的层级1库2表3列
        List<String> hiddenList=StringUtil.splitHidden(TConstants.HIVEDATABASEHIDDEN);//要屏蔽的数据库
        List<String> dataFromServer = new ArrayList<>();
        if (resourceId == 0) {//同步库
            dataFromServer = hiveService.getDatabases();
            level = 1;
        } else {
            level = parent.getLevel() + 1;
            if (parent.getLevel() == 1) {
                dataFromServer = hiveService.getTables(parent.getDatabaseName());
            } else {
                Map<String, Object> cols = hiveService.getColInfo(parent.getDatabaseName(), parent.getTableName());
                if (cols != null && cols.size() > 0 && cols.get("colNames") != null) {
                    dataFromServer = (List<String>) cols.get("colNames");
                }
            }
        }
        if (dataFromServer != null && dataFromServer.size() > 0) {
            Integer insertId = null;
            for (String data : dataFromServer) {
                HiveResourceEntity exist = null;
                switch (level) {
                    case 1:
                        exist = hiveResourceService.findByDatabaseName(data);
                        break;
                    case 2:
                        exist = hiveResourceService.findByTableNameAndParentId(data, parent.getId());
                        break;
                    case 3:
                        exist = hiveResourceService.findByColumnNameAndParentId(data, parent.getId());
                        break;
                    default:
                        break;
                }
                if (exist == null) {
                    HiveResourceEntity dataHive = new HiveResourceEntity();
                    dataHive.setInsDate(now);
                    dataHive.setUpdDate(now);
                    dataHive.setLevel(level);
                    dataHive.setOwner(parent != null ? parent.getOwner() : TConstants.ADMIN_ID);//设置为父资源属主，然后分配里再具体赋权
                    dataHive.setStatus(TConstants.RES_STATUS_AVAILABLE);
                    if (level == 1) {
                        dataHive.setDatabaseName(data);
                        dataHive.setParentId(0);
                        if(hiddenList.contains(data)){
                            dataHive.setStatus(0);//默认隐藏
                        }
                    } else if (level == 2) {
                        dataHive.setTableName(data);
                        dataHive.setParentId(parent.getId());
                        dataHive.setDatabaseName(parent.getDatabaseName());
                        if(hiddenList.contains(parent.getDatabaseName())){
                            dataHive.setStatus(0);//默认隐藏
                        }
                    } else {
                        dataHive.setColumnName(data);
                        dataHive.setParentId(parent.getId());
                        dataHive.setDatabaseName(parent.getDatabaseName());
                        dataHive.setTableName(parent.getTableName());
                    }
                    hiveResourceService.save(dataHive);
                    insertId = dataHive.getId();
                    up += 1;

                    if (dataHive.getParentId() == 0)
                     {//管理員同步到了頂級資源才加權限，用户创建的时候就有权限，级联权限
                        UserResourceRelationEntity ur = userResRelationSerivce.findFirstByResourceIdAndUserIdAndResourceType(dataHive.getId(), currentUser.getId(), ResourceTypeEnum.HIVE.name());
                        if (ur == null) {
                            ur = new UserResourceRelationEntity();
                            ur.setResourceContent(data);
                            ur.setUpdDate(now);
                            ur.setInsDate(now);
                            ur.setAuthor(powerStr);
                            ur.setStatus(TConstants.RES_STATUS_AVAILABLE);
                            ur.setResourceLevel(dataHive.getLevel());
                            if(TConstants.ADMIN_ID.equals(dataHive.getOwner()) ){
                                ur.setUserId(currentUser.getId());
                            }else {
                                ur.setUserId(currentUser.getId());

                            }
                            ur.setResourceId(dataHive.getId());
                            ur.setResourceType(ResourceTypeEnum.HIVE.name());
                            userResRelationSerivce.save(ur);
                            try {
                                //同步数据可能存在删了再同步这种脏数据，所以这里加个异常
                                rangerService.setPermissionInRanger(ResourceTypeEnum.HIVE.name().toLowerCase(), data + "|*|*", powerStr, currentUser.getName());
                            }catch (Exception e){
                                logger.error("设置hive权限出错: {}, {}, {}",data + "|*|*",powerStr,currentUser.getName());
                            }
                        }
                    }

                }else{
                    insertId=exist.getId();//如果已经存在这个了直接返回。更新表的时候需要
                    if(level==1){
                        if(hiddenList.contains(data)){
                            exist.setStatus(0);//默认隐藏
                            hiveResourceService.save(exist);
                        }
                    }

                }

                if (level == 2 && insertId != null) {
                    sync(insertId, null);
                }
            }
            delFromSync(dataFromServer, resourceId, level);
        } else {
            dataFromServer = new ArrayList<>();
            delFromSync(dataFromServer, resourceId, level);
        }
        result.setData(up);
        return result;
    }

    List<HiveResourceEntity> findByLevelAndStatus(Integer level, Integer status) {
        return hiveResourceService.findByLevelAndStatus(level, status);
    }

    List<HiveResourceEntity> findByLevelAndStatusAndOwner(Integer level, Integer status, Integer owner) {
        return hiveResourceService.findByLevelAndStatusAndOwner(level, status, owner);
    }

    public boolean existDatabase(String database) {
        List<String> dataList = hiveService.getDatabases();
        if (dataList != null && dataList.size() > 0) {
            return dataList.contains(database);
        }
        return false;
    }

    /**
     * 根据资源名找资源ID，同步时使用
     *
     * @param resourceName
     * @return
     */
    public Integer findResourceIdByName(String resourceName) {
        if (StringUtil.isEmpty(resourceName)) {
            return null;
        }
        String[] resource = resourceName.split("\\|");
        if (resource.length == 0) {
            return null;
        } else if (resource.length == 1 && !StringUtil.isEmpty(resource[0])) {
            HiveResourceEntity hive = hiveResourceService.findByDatabaseName(resource[0]);
            if (hive != null) return hive.getId();
        } else if (resource.length == 2 && !StringUtil.isEmpty(resource[0]) && !StringUtil.isEmpty(resource[1])) {
            HiveResourceEntity data = hiveResourceService.findByDatabaseName(resource[0]);
            if (data != null) {
                HiveResourceEntity table = hiveResourceService.findByTableNameAndParentId(resource[1], data.getId());
                if (table != null) return table.getId();
            }
        }
        return null;
    }

    /**
     * hive同步时删除服务器上不存在数据
     *
     * @param dataFromServer 服务器上数据
     * @param id             资源ID
     * @param level          级别 1库2表3列
     * @return
     */
    // @Transactional(rollbackFor = Exception.class)
    public Integer delFromSync(List<String> dataFromServer, Integer id, Integer level) {
        List<HiveResourceEntity> dataFromMysql = hiveResourceService.findByParentId(id);//从数据库中读取到的资源
        Integer delNum = 0;
        if (dataFromMysql != null && dataFromMysql.size() > 0) {
            for (HiveResourceEntity hi : dataFromMysql) {
                String resource = "";
                if (level == 1) {
                    resource = hi.getDatabaseName();
                } else if (level == 2) {
                    resource = hi.getTableName();
                } else if (level == 3) {
                    resource = hi.getColumnName();
                }
                if (!StringUtil.isEmpty(resource) && !dataFromServer.contains(resource)) {//服务器上已经不存在了
                    delRes(hi.getId());
                    delNum++;
                }
            }
        }
        return delNum;
    }

    protected Integer delRes(Integer resourceId) {
        HiveResourceEntity hive = hiveResourceService.findHiveResourceEntityById(resourceId);
        if (hive == null) {
            return 0;
        }
        Integer delNum = 0;
        if (hive.getLevel() == 1) {//删库，清空权限
            delNum = delDatabase(hive, 0);
        } else if (hive.getLevel() == 2) {
            delNum = delTable(hive, 0);
        } else if (hive.getLevel() == 3) {
            delNum = delColumn(hive, 0);
        }
        return delNum;
    }

    /**
     * 删除数据，这里需要优化
     *
     * @param hive
     * @return
     */
    @Transactional(transactionManager = "transactionManagerDataspace")
    protected Integer delDatabase(HiveResourceEntity hive, Integer keepData) {
        List<UserResourceRelationEntity> urs = userResRelationSerivce.findByResourceIdAndResourceType(hive.getId(), ResourceTypeEnum.HIVE.getResourceType());
        if (urs != null && urs.size() > 0) {
            List<Integer> uid = new ArrayList<>();
            for (UserResourceRelationEntity ur : urs) {
                uid.add(ur.getUserId());
            }
            List<String> usernameList = userService.findByIdIn(uid).stream().map(o -> o.getName()).collect(Collectors.toList());
            String resource = hive.getDatabaseName() + "|*|*";
            rangerService.setPermissionInRanger(ResourceTypeEnum.HIVE.name().toLowerCase(), resource, "", StringUtil.concat(usernameList, "|"));
            userResRelationSerivce.delByResourceId(hive.getId(), ResourceTypeEnum.HIVE.getResourceType());
        }
        Integer result = 0;
        if (keepData == 0) {
            hiveResourceService.deleteById(hive.getId());
        } else {
            hive.setStatus(0);
            hiveResourceService.save(hive);
        }
        List<HiveResourceEntity> hiveResourceEntityList = hiveResourceService.findByParentId(hive.getId());
        if (hiveResourceEntityList != null && hiveResourceEntityList.size() > 0) {
            for (HiveResourceEntity hiveResourceEntity : hiveResourceEntityList) {
                result += delTable(hiveResourceEntity, keepData);
            }
        }
        return result;
    }

    protected Integer delTable(HiveResourceEntity hive, Integer keepData) {
        List<UserResourceRelationEntity> urs = userResRelationSerivce.findByResourceIdAndResourceType(hive.getId(), ResourceTypeEnum.HIVE.getResourceType());
        if (urs != null && urs.size() > 0) {
            List<Integer> uid = new ArrayList<>();
            for (UserResourceRelationEntity ur : urs) {
                uid.add(ur.getUserId());
            }
            List<String> usernameList = userService.findByIdIn(uid).stream().map(o -> o.getName()).collect(Collectors.toList());
            String resource = hive.getDatabaseName() + "|" + hive.getTableName() + "|*";
            rangerService.setPermissionInRanger(ResourceTypeEnum.HIVE.name().toLowerCase(), resource, "", StringUtil.concat(usernameList, "|"));
            userResRelationSerivce.delByResourceId(hive.getId(), ResourceTypeEnum.HIVE.getResourceType());
        }
        Integer result = 0;
        if (keepData == 0) {
            hiveResourceService.deleteById(hive.getId());
        } else {
            hive.setStatus(0);
            hiveResourceService.save(hive);
        }
        List<HiveResourceEntity> hiveResourceEntityList = hiveResourceService.findByParentId(hive.getId());
        if (hiveResourceEntityList != null && hiveResourceEntityList.size() > 0) {
            for (HiveResourceEntity hiveResourceEntity : hiveResourceEntityList) {
                result += delColumn(hiveResourceEntity, keepData);
            }
        }
        return result;
    }

    @Transactional(transactionManager = "transactionManagerDataspace")
    protected Integer delColumn(HiveResourceEntity hive, Integer keepData) {
        if (keepData == 0) {
            hiveResourceService.deleteById(hive.getId());
        } else {
            hive.setStatus(0);
            hiveResourceService.save(hive);
        }
        List<UserResourceRelationEntity> urs = userResRelationSerivce.findByResourceIdAndResourceType(hive.getId(), ResourceTypeEnum.HIVE.getResourceType());
        if (urs == null || urs.size() == 0) {
            return 0;
        }
        List<Integer> uid = new ArrayList<>();
        for (UserResourceRelationEntity ur : urs) {
            uid.add(ur.getUserId());
        }
        List<String> usernameList = userService.findByIdIn(uid).stream().map(o -> o.getName()).collect(Collectors.toList());
        String resource = hive.getDatabaseName() + "|" + hive.getTableName() + "|" + hive.getColumnName();
        rangerService.setPermissionInRanger(ResourceTypeEnum.HIVE.name().toLowerCase(), resource, "", StringUtil.concat(usernameList, "|"));
        Integer result = userResRelationSerivce.delByResourceId(hive.getId(), ResourceTypeEnum.HIVE.getResourceType());
        return result;
    }
}
